import { Express, Request, Response } from 'express';
import { ServiceManager, ServiceConfig } from './services/ServiceManager';

export function setupRoutes(app: Express, serviceManager: ServiceManager) {
  
  // 获取所有服务状态
  app.get('/api/services', (req: Request, res: Response) => {
    try {
      const services = serviceManager.getServicesStatus();
      res.json({ success: true, data: services });
    } catch (error) {
      res.status(500).json({ 
        success: false, 
        error: error instanceof Error ? error.message : '获取服务列表失败' 
      });
    }
  });

  // 启动服务
  app.post('/api/services/:id/start', async (req: Request, res: Response) => {
    try {
      const serviceId = req.params.id;
      const success = await serviceManager.startService(serviceId);
      
      if (success) {
        res.json({ success: true, message: '服务启动成功' });
      } else {
        res.status(400).json({ success: false, error: '服务启动失败' });
      }
    } catch (error) {
      res.status(500).json({ 
        success: false, 
        error: error instanceof Error ? error.message : '启动服务时发生错误' 
      });
    }
  });

  // 停止服务
  app.post('/api/services/:id/stop', async (req: Request, res: Response) => {
    try {
      const serviceId = req.params.id;
      const success = await serviceManager.stopService(serviceId);
      
      if (success) {
        res.json({ success: true, message: '服务停止成功' });
      } else {
        res.status(400).json({ success: false, error: '服务停止失败' });
      }
    } catch (error) {
      res.status(500).json({ 
        success: false, 
        error: error instanceof Error ? error.message : '停止服务时发生错误' 
      });
    }
  });

  // 重启服务
  app.post('/api/services/:id/restart', async (req: Request, res: Response) => {
    try {
      const serviceId = req.params.id;
      const success = await serviceManager.restartService(serviceId);
      
      if (success) {
        res.json({ success: true, message: '服务重启成功' });
      } else {
        res.status(400).json({ success: false, error: '服务重启失败' });
      }
    } catch (error) {
      res.status(500).json({ 
        success: false, 
        error: error instanceof Error ? error.message : '重启服务时发生错误' 
      });
    }
  });

  // 获取服务日志
  app.get('/api/services/:id/logs', (req: Request, res: Response) => {
    try {
      const serviceId = req.params.id;
      const lines = parseInt(req.query.lines as string) || 100;
      const logs = serviceManager.getServiceLogs(serviceId, lines);
      
      res.json({ success: true, data: logs });
    } catch (error) {
      res.status(500).json({ 
        success: false, 
        error: error instanceof Error ? error.message : '获取日志失败' 
      });
    }
  });

  // 添加新服务
  app.post('/api/services', (req: Request, res: Response) => {
    try {
      const serviceConfig: ServiceConfig = req.body;
      
      console.log('[添加服务] 收到请求:', JSON.stringify(serviceConfig, null, 2));
      
      // 验证必要字段
      if (!serviceConfig.id) {
        console.error('[添加服务] 缺少 id 字段');
        return res.status(400).json({ 
          success: false, 
          error: '缺少必要字段: id' 
        });
      }
      
      if (!serviceConfig.name) {
        console.error('[添加服务] 缺少 name 字段');
        return res.status(400).json({ 
          success: false, 
          error: '缺少必要字段: name (服务名称)' 
        });
      }
      
      if (!serviceConfig.executablePath) {
        console.error('[添加服务] 缺少 executablePath 字段');
        return res.status(400).json({ 
          success: false, 
          error: '缺少必要字段: executablePath (可执行文件路径)' 
        });
      }

      console.log('[添加服务] 字段验证通过，开始添加服务...');
      
      const success = serviceManager.addService(serviceConfig);
      
      if (success) {
        console.log('[添加服务] 成功添加服务:', serviceConfig.name);
        res.json({ 
          success: true, 
          message: `服务 "${serviceConfig.name}" 添加成功` 
        });
      } else {
        console.error('[添加服务] serviceManager.addService 返回 false');
        res.status(400).json({ 
          success: false, 
          error: '服务添加失败，可能是服务ID已存在或配置文件写入失败，请检查后端日志' 
        });
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      const errorStack = error instanceof Error ? error.stack : '';
      
      console.error('[添加服务] 异常:', errorMessage);
      console.error('[添加服务] 堆栈:', errorStack);
      
      // 根据错误类型提供更具体的提示
      let userMessage = '添加服务时发生错误';
      
      if (errorMessage.includes('EACCES') || errorMessage.includes('permission')) {
        userMessage = '权限不足：无法写入配置文件。请以管理员身份运行 fix-iis-permissions.ps1 脚本修复权限';
      } else if (errorMessage.includes('ENOENT')) {
        userMessage = '文件或目录不存在：' + errorMessage;
      } else if (errorMessage.includes('EEXIST')) {
        userMessage = '服务ID已存在，请使用不同的服务名称';
      }
      
      res.status(500).json({ 
        success: false, 
        error: userMessage,
        details: errorMessage // 提供详细错误信息供调试
      });
    }
  });

  // 删除服务
  app.delete('/api/services/:id', async (req: Request, res: Response) => {
    try {
      const serviceId = req.params.id;
      const success = await serviceManager.removeService(serviceId);
      
      if (success) {
        res.json({ success: true, message: '服务删除成功' });
      } else {
        res.status(400).json({ success: false, error: '服务删除失败' });
      }
    } catch (error) {
      res.status(500).json({ 
        success: false, 
        error: error instanceof Error ? error.message : '删除服务时发生错误' 
      });
    }
  });

  // 健康检查
  app.get('/api/health', (req: Request, res: Response) => {
    res.json({ 
      success: true, 
      message: '服务管理器运行正常',
      timestamp: new Date().toISOString()
    });
  });
}